import React, { useState, useRef, useEffect } from 'react';
import { UploadOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { Button, Upload as AntUpload, message, Modal, Image, Space } from 'antd';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import ApiService, { ProductImage } from '../services/api';

interface ImageUploadProps {
  productId?: number;
  onImagesUploaded?: (images: ProductImage[]) => void;
  onImagesDeleted?: (imageIds: number[]) => void;
  maxCount?: number;
  disabled?: boolean;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  productId,
  onImagesUploaded,
  onImagesDeleted,
  maxCount = 10,
  disabled = false
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  // 当productId变化时，加载已有的图片
  useEffect(() => {
    if (productId) {
      loadExistingImages();
    } else {
      setFileList([]);
    }
  }, [productId]);

  const loadExistingImages = async () => {
    if (!productId) return;
    
    try {
      const images = await ApiService.getImages(productId);
      const existingFileList = images.map(image => ({
        uid: image.id.toString(),
        name: image.original_filename,
        status: 'done' as const,
        url: ApiService.getImageUrl(image.id),
        thumbUrl: ApiService.getImageUrl(image.id),
        size: image.file_size,
        type: image.content_type,
      }));
      setFileList(existingFileList);
    } catch (error) {
      console.error('加载已有图片失败:', error);
    }
  };

  const handleUpload = async (files: File[]) => {
    if (files.length === 0) return;

    setUploading(true);
    try {
      const uploadedImages = await ApiService.uploadImages(files, productId);
      message.success(`成功上传 ${uploadedImages.length} 张图片`);
      
      // 更新文件列表
      const newFileList = uploadedImages.map((image, index) => ({
        uid: image.id.toString(),
        name: image.original_filename,
        status: 'done' as const,
        url: ApiService.getImageUrl(image.id),
        thumbUrl: ApiService.getImageUrl(image.id),
        size: image.file_size,
        type: image.content_type,
      }));
      
      setFileList(prev => [...prev, ...newFileList]);
      onImagesUploaded?.(uploadedImages);
      
      // 如果上传时没有productId，提示用户
      if (!productId) {
        message.info('图片已上传，保存商品信息后会自动关联');
      }
    } catch (error: any) {
      message.error(`上传失败: ${error.response?.data?.detail || error.message}`);
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (file: UploadFile) => {
    try {
      await ApiService.deleteImage(parseInt(file.uid));
      setFileList(prev => prev.filter(item => item.uid !== file.uid));
      onImagesDeleted?.([parseInt(file.uid)]);
      message.success('图片删除成功');
    } catch (error: any) {
      message.error(`删除失败: ${error.response?.data?.detail || error.message}`);
    }
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = error => reject(error);
    });

  const uploadProps: UploadProps = {
    onRemove: handleDelete,
    onPreview: handlePreview,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      return false; // 阻止自动上传
    },
    fileList,
    disabled: disabled || uploading,
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);
    if (files.length > 0) {
      handleUpload(files);
    }
    // 清空input值，允许重复选择同一文件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%' }}>
        <div>
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*"
            onChange={handleFileSelect}
            style={{ display: 'none' }}
          />
          <Button
            icon={<UploadOutlined />}
            onClick={() => fileInputRef.current?.click()}
            loading={uploading}
            disabled={disabled || fileList.length >= maxCount}
          >
            选择图片
          </Button>
          <span style={{ marginLeft: 8, color: '#666' }}>
            最多可上传 {maxCount} 张图片，每张不超过 5MB
          </span>
        </div>
        
        <AntUpload
          listType="picture-card"
          {...uploadProps}
          showUploadList={{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: false,
          }}
        />
      </Space>

      <Modal
        open={previewVisible}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default ImageUpload; 